﻿// Admin.NET 项目的版权、商标、专利和其他相关权利均受相应法律法规的保护。使用本项目应遵守相关法律法规和许可证的要求。
//
// 本项目主要遵循 MIT 许可证和 Apache 许可证（版本 2.0）进行分发和使用。许可证位于源代码树根目录中的 LICENSE-MIT 和 LICENSE-APACHE 文件。
//
// 不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动！任何基于本项目二次开发而产生的一切法律纠纷和责任，我们不承担任何责任！

using Admin.NET.Core.Service;
using Microsoft.AspNetCore.Http;
using static SKIT.FlurlHttpClient.Wechat.TenpayV3.Models.CreateFundsToOverseaOrderRequest.Types;

namespace Admin.NET.Application;

/// <summary>
/// 车辆求购信息表-竞拍表服务 🧩
/// </summary>
[ApiDescriptionSettings(ApplicationConst.GroupName, Order = 100)]
public class AppVehicleBidService : IDynamicApiController, ITransient
{
    private readonly SqlSugarRepository<AppVehicleBid> _appVehicleBidRep;
    private readonly ISqlSugarClient _sqlSugarClient;
    private readonly SysDictTypeService _sysDictTypeService;
    private readonly AppNotificationService _appNotificationService;
    private readonly UserManager _userManager;

    public AppVehicleBidService(SqlSugarRepository<AppVehicleBid> appVehicleBidRep, ISqlSugarClient sqlSugarClient, SysDictTypeService sysDictTypeService, AppNotificationService appNotificationService, UserManager userManager)
    {
        _appVehicleBidRep = appVehicleBidRep;
        _sqlSugarClient = sqlSugarClient;
        _sysDictTypeService = sysDictTypeService;
        _appNotificationService = appNotificationService;
        this._userManager = userManager;
    }

    /// <summary>
    /// 分页查询车辆求购信息表-竞拍表 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("分页查询车辆求购信息表-竞拍表")]
    [ApiDescriptionSettings(Name = "Page"), HttpPost]
    public async Task<SqlSugarPagedList<AppVehicleBidOutput>> Page(PageAppVehicleBidInput input)
    {
        input.Keyword = input.Keyword?.Trim();
        var query = _appVehicleBidRep.AsQueryable()
            .WhereIF(input.PurchaseId != null, u => u.PurchaseId == input.PurchaseId)
            .WhereIF(input.SellerId != null, u => u.SellerId == input.SellerId)
            .WhereIF(input.Status != null, u => (int)u.Status == input.Status)
            .LeftJoin<AppVehiclePurchase>((u, purchase) => u.PurchaseId == purchase.Id)
            .LeftJoin<SysUser>((u, purchase, seller) => u.SellerId == seller.Id)
            .Select((u, purchase, seller) => new AppVehicleBidOutput
            {
                Id = u.Id,
                PurchaseId = u.PurchaseId,
                PurchaseFkDisplayName = $"{purchase.BrandId}-{purchase.ModelId}",
                SellerId = u.SellerId,
                SellerFkDisplayName = $"{seller.RealName}",
                BidPrice = u.BidPrice,
                Description = u.Description,
                Status = (int)u.Status,
                TenantId = u.TenantId,
                CreateTime = u.CreateTime,
                UpdateTime = u.UpdateTime,
                CreateUserId = u.CreateUserId,
                CreateUserName = u.CreateUserName,
                UpdateUserId = u.UpdateUserId,
                UpdateUserName = u.UpdateUserName,
                IsDelete = u.IsDelete,
            });
		return await query.OrderBuilder(input).ToPagedListAsync(input.Page, input.PageSize);
    }

    /// <summary>
    /// 查询车辆求购信息表-竞拍表 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("查询车辆求购信息表-竞拍表")]
    [ApiDescriptionSettings(Name = "List"), HttpPost]
    public async Task<List<AppVehicleBidOutput>> List(PageAppVehicleBidInput input)
    {
        bool isSelf=false;
        input.Keyword = input.Keyword?.Trim();

        var purchase = new AppVehiclePurchase { };
        if (input.PurchaseId > 0)
        {
            purchase = await _appVehicleBidRep.ChangeRepository<SqlSugarRepository<AppVehiclePurchase>>().AsQueryable().FirstAsync(u => u.Id == input.PurchaseId);
            if (purchase == null) throw Oops.Oh(ErrorCodeEnum.D1002);
            isSelf = purchase.CreateUserId==_userManager.UserId;
        }
        var query = _appVehicleBidRep.AsQueryable()
            .WhereIF(input.PurchaseId != null, u => u.PurchaseId == input.PurchaseId)
            .WhereIF(input.SellerId != null, u => u.SellerId == input.SellerId)
            .WhereIF(input.Status != null, u => (int)u.Status == input.Status)
            .WhereIF(!isSelf, u => u.SellerId == _userManager.UserId)
            .LeftJoin<AppVehiclePurchase>((u, purchase) => u.PurchaseId == purchase.Id)
            .LeftJoin<SysUser>((u, purchase, seller) => u.SellerId == seller.Id)
            .Select((u, purchase, seller) => new AppVehicleBidOutput
            {
                Id = u.Id,
                PurchaseId = u.PurchaseId,
                PurchaseFkDisplayName = $"{purchase.BrandId}-{purchase.ModelId}",
                SellerId = u.SellerId,
                SellerAvatar=seller.Avatar,
                SellerFkDisplayName = $"{seller.RealName}",
                BidPrice = u.BidPrice,
                Description = u.Description,
                Status = (int)u.Status,
                TenantId = u.TenantId,
                CreateTime = u.CreateTime,
                UpdateTime = u.UpdateTime,
                CreateUserId = u.CreateUserId,
                CreateUserName = u.CreateUserName,
                UpdateUserId = u.UpdateUserId,
                UpdateUserName = u.UpdateUserName,
                IsDelete = u.IsDelete,
                UserId = seller.Id,
                Avatar = seller.Avatar,
                Phone = u.Status == AuctionStatusEnum.Won? seller.Phone: "",
                GoodFeedback = SqlFunc.Subqueryable<AppVehicleTransactionFeedback>().Where(b => b.TargetUserId == seller.Id &&(int)b.Rating > 3  && b.IsDelete == false).Count(),
                BadFeedback = SqlFunc.Subqueryable<AppVehicleTransactionFeedback>().Where(b => b.TargetUserId == seller.Id && (int)b.Rating <= 3 && b.IsDelete == false).Count()
            });
        return await query.OrderBuilder(input).ToListAsync();
    }

    /// <summary>
    /// 获取车辆求购信息表-竞拍表详情 ℹ️
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("获取车辆求购信息表-竞拍表详情")]
    [ApiDescriptionSettings(Name = "Detail"), HttpGet]
    public async Task<AppVehicleBid> Detail([FromQuery] QueryByIdAppVehicleBidInput input)
    {
        return await _appVehicleBidRep.GetFirstAsync(u => u.Id == input.Id);
    }

    /// <summary>
    /// 增加车辆求购信息表-竞拍表 ➕
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("增加车辆求购信息表-竞拍表")]
    [ApiDescriptionSettings(Name = "Add"), HttpPost]
    public async Task<long> Add(AddAppVehicleBidInput input)
    {
        if (input.PurchaseId > 0)
        {
          var purchase = await  _sqlSugarClient.Queryable<AppVehiclePurchase>().Where(u => u.Id == input.PurchaseId).FirstAsync();

            await _appNotificationService.Add(new AddAppNotificationInput
            {
                PurchaseId = purchase.Id,
                ReceiverId = purchase.BuyerId,
                Type = NotificationTypeEnum.NewBid,
                Title = "新抢单通知",
            });
        }
        var entity = input.Adapt<AppVehicleBid>();
        entity.SellerId = _userManager.UserId;
        return await _appVehicleBidRep.InsertAsync(entity) ? entity.Id : 0;
    }

    /// <summary>
    /// 更新车辆求购信息表-竞拍表 ✏️
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("更新车辆求购信息表-竞拍表")]
    [ApiDescriptionSettings(Name = "Update"), HttpPost]
    public async Task Update(UpdateAppVehicleBidInput input)
    {
        var entity = input.Adapt<AppVehicleBid>();
        await _appVehicleBidRep.AsUpdateable(entity)
        .ExecuteCommandAsync();
    }

    /// <summary>
    /// 更新车辆求购信息表状态-竞拍表 ✏️
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("更新车辆求购信息表状态-竞拍表")]
    [ApiDescriptionSettings(Name = "UpdateStatus"), HttpPost]
    public async Task UpdateStatus(UpdateAppVehicleBidInput input)
    {
        var entity = input.Adapt<AppVehicleBid>();
        await _appVehicleBidRep.AsUpdateable(entity).UpdateColumns(u=>new {u.Status})
        .ExecuteCommandAsync();
        if (entity.Status == AuctionStatusEnum.Won)
        {
         var bidInfo =  await _appVehicleBidRep.GetFirstAsync(u => u.Id == input.Id);
            await _appNotificationService.Add(new AddAppNotificationInput
            {
                PurchaseId = bidInfo.PurchaseId,
                ReceiverId = bidInfo.SellerId,
                Type = NotificationTypeEnum.SnatchingSuccess,
                Title = "抢单成功",
            });
        }
    }

    /// <summary>
    /// 删除车辆求购信息表-竞拍表 ❌
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("删除车辆求购信息表-竞拍表")]
    [ApiDescriptionSettings(Name = "Delete"), HttpPost]
    public async Task Delete(DeleteAppVehicleBidInput input)
    {
        var entity = await _appVehicleBidRep.GetFirstAsync(u => u.Id == input.Id) ?? throw Oops.Oh(ErrorCodeEnum.D1002);
        await _appVehicleBidRep.FakeDeleteAsync(entity);   //假删除
        //await _appVehicleBidRep.DeleteAsync(entity);   //真删除
    }

    /// <summary>
    /// 批量删除车辆求购信息表-竞拍表 ❌
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("批量删除车辆求购信息表-竞拍表")]
    [ApiDescriptionSettings(Name = "BatchDelete"), HttpPost]
    public async Task<int> BatchDelete([Required(ErrorMessage = "主键列表不能为空")]List<DeleteAppVehicleBidInput> input)
    {
        var exp = Expressionable.Create<AppVehicleBid>();
        foreach (var row in input) exp = exp.Or(it => it.Id == row.Id);
        var list = await _appVehicleBidRep.AsQueryable().Where(exp.ToExpression()).ToListAsync();
   
        return await _appVehicleBidRep.FakeDeleteAsync(list);   //假删除
        //return await _appVehicleBidRep.DeleteAsync(list);   //真删除
    }
    
    /// <summary>
    /// 获取下拉列表数据 🔖
    /// </summary>
    /// <returns></returns>
    [DisplayName("获取下拉列表数据")]
    [ApiDescriptionSettings(Name = "DropdownData"), HttpPost]
    public async Task<Dictionary<string, dynamic>> DropdownData(DropdownDataAppVehicleBidInput input)
    {
        var purchaseIdData = await _appVehicleBidRep.Context.Queryable<AppVehiclePurchase>()
            .InnerJoinIF<AppVehicleBid>(input.FromPage, (u, r) => u.Id == r.PurchaseId)
            .Select(u => new {
                Value = u.Id,
                Label = $"{u.BrandId}-{u.ModelId}"
            }).ToListAsync();
        var sellerIdData = await _appVehicleBidRep.Context.Queryable<SysUser>()
            .InnerJoinIF<AppVehicleBid>(input.FromPage, (u, r) => u.Id == r.SellerId)
            .Select(u => new {
                Value = u.Id,
                Label = $"{u.RealName}"
            }).ToListAsync();
        return new Dictionary<string, dynamic>
        {
            { "purchaseId", purchaseIdData },
            { "sellerId", sellerIdData },
        };
    }
    
    /// <summary>
    /// 导出车辆求购信息表-竞拍表记录 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    //[DisplayName("导出车辆求购信息表-竞拍表记录")]
    //[ApiDescriptionSettings(Name = "Export"), HttpPost, NonUnify]
    //public async Task<IActionResult> Export(PageAppVehicleBidInput input)
    //{
    //    var list = (await Page(input)).Items?.Adapt<List<ExportAppVehicleBidOutput>>() ?? new();
    //    if (input.SelectKeyList?.Count > 0) list = list.Where(x => input.SelectKeyList.Contains(x.Id)).ToList();
    //    var statusDictMap = _sysDictTypeService.GetDataList(new GetDataDictTypeInput { Code = "AuctionStatus" }).Result.ToDictionary(x => x.Value, x => x.Label);
    //    list.ForEach(e => {
    //        e.StatusDictLabel = statusDictMap.GetValueOrDefault(e.Status ?? "", e.Status);
    //    });
    //    return ExcelHelper.ExportTemplate(list, "车辆求购信息表-竞拍表导出记录");
    //}
    
    /// <summary>
    /// 下载车辆求购信息表-竞拍表数据导入模板 ⬇️
    /// </summary>
    /// <returns></returns>
    [DisplayName("下载车辆求购信息表-竞拍表数据导入模板")]
    [ApiDescriptionSettings(Name = "Import"), HttpGet, NonUnify]
    public IActionResult DownloadTemplate()
    {
        return ExcelHelper.ExportTemplate(new List<ExportAppVehicleBidOutput>(), "车辆求购信息表-竞拍表导入模板", (_, info) =>
        {
            if (nameof(ExportAppVehicleBidOutput.PurchaseFkDisplayName) == info.Name) return _appVehicleBidRep.Context.Queryable<AppVehiclePurchase>().Select(u => $"{u.BrandId}-{u.ModelId}").Distinct().ToList();
            if (nameof(ExportAppVehicleBidOutput.SellerFkDisplayName) == info.Name) return _appVehicleBidRep.Context.Queryable<SysUser>().Select(u => $"{u.RealName}").Distinct().ToList();
            return null;
        });
    }
    
    /// <summary>
    /// 导入车辆求购信息表-竞拍表记录 💾
    /// </summary>
    /// <returns></returns>
    [DisplayName("导入车辆求购信息表-竞拍表记录")]
    [ApiDescriptionSettings(Name = "Import"), HttpPost, NonUnify, UnitOfWork]
    public IActionResult ImportData([Required] IFormFile file)
    {
        lock (this)
        {
            var statusDictMap = _sysDictTypeService.GetDataList(new GetDataDictTypeInput { Code = "AuctionStatus" }).Result.ToDictionary(x => x.Label!, x => x.Value);
            var stream = ExcelHelper.ImportData<ImportAppVehicleBidInput, AppVehicleBid>(file, (list, markerErrorAction) =>
            {
                _sqlSugarClient.Utilities.PageEach(list, 2048, pageItems =>
                {
                    // 链接 求购信息表
                    var purchaseIdLabelList = pageItems.Where(x => x.PurchaseFkDisplayName != null).Select(x => x.PurchaseFkDisplayName).Distinct().ToList();
                    if (purchaseIdLabelList.Any()) {
                        var purchaseIdLinkMap = _appVehicleBidRep.Context.Queryable<AppVehiclePurchase>().Where(u => purchaseIdLabelList.Contains($"{u.BrandId}-{u.ModelId}")).ToList().ToDictionary(u => $"{u.BrandId}-{u.ModelId}", u => u.Id);
                        pageItems.ForEach(e => {
                            e.PurchaseId = purchaseIdLinkMap.GetValueOrDefault(e.PurchaseFkDisplayName ?? "");
                            if (e.PurchaseId == null) e.Error = "求购信息表链接失败";
                        });
                    }
                    // 链接 卖家Id
                    var sellerIdLabelList = pageItems.Where(x => x.SellerFkDisplayName != null).Select(x => x.SellerFkDisplayName).Distinct().ToList();
                    if (sellerIdLabelList.Any()) {
                        var sellerIdLinkMap = _appVehicleBidRep.Context.Queryable<SysUser>().Where(u => sellerIdLabelList.Contains($"{u.RealName}")).ToList().ToDictionary(u => $"{u.RealName}", u => u.Id);
                        pageItems.ForEach(e => {
                            e.SellerId = sellerIdLinkMap.GetValueOrDefault(e.SellerFkDisplayName ?? "");
                            if (e.SellerId == null) e.Error = "卖家Id链接失败";
                        });
                    }
                    
                    // 映射字典值
                    //foreach(var item in pageItems) {
                    //    if (string.IsNullOrWhiteSpace(item.StatusDictLabel)) continue;
                    //    item.Status = statusDictMap.GetValueOrDefault(item.StatusDictLabel);
                    //    if (item.Status == null) item.Error = "状态字典映射失败";
                    //}
                    
                    // 校验并过滤必填基本类型为null的字段
                    var rows = pageItems.Where(x => {
                        if (!string.IsNullOrWhiteSpace(x.Error)) return false;
                        if (x.PurchaseId == null){
                            x.Error = "求购信息表不能为空";
                            return false;
                        }
                        if (!string.IsNullOrWhiteSpace(x.Error)) return false;
                        if (x.SellerId == null){
                            x.Error = "卖家Id不能为空";
                            return false;
                        }
                        if (!string.IsNullOrWhiteSpace(x.Error)) return false;
                        if (x.Status == null){
                            x.Error = "状态不能为空";
                            return false;
                        }
                        return true;
                    }).Adapt<List<AppVehicleBid>>();
                    
                    var storageable = _appVehicleBidRep.Context.Storageable(rows)
                        .SplitError(it => string.IsNullOrWhiteSpace(it.Item.Description), "车辆描述不能为空")
                        .SplitError(it => it.Item.Description?.Length > 500, "车辆描述长度不能超过500个字符")
                        .SplitInsert(_ => true)
                        .ToStorage();
                    
                    storageable.BulkCopy();
                    storageable.BulkUpdate();
                    
                    // 标记错误信息
                    markerErrorAction.Invoke(storageable, pageItems, rows);
                });
            });
            
            return stream;
        }
    }

}
